const router = require('koa-router')();
const gravatar = require('gravatar');
const jwt = require('jsonwebtoken');
const passport = require('koa-passport');

const { encrypt, decrypt } = require('../../utils/passwordHandler');
const validateRegisterInput = require('../../validator/register');
const validateLoginInput = require('../../validator/login');
const { secretOrKey } = require('../../config/keys');

// 引入 User
const User = require('../../models/UserModel');

/**
 * @route GET api/users/test
 * @desc 测试接口地址
 * @access 接口是公开的
 */
router.get('/test', async ctx => {
    ctx.status = 200;
    ctx.body = { msg: 'user koa' };
});

/**
 * @route POST api/users/register
 * @desc 测试接口地址
 * @access 接口是公开的
 */
router.post('/register', async ctx => {
    const { name, password, email } = ctx.request.body;

    const { errors, isValid } = validateRegisterInput(ctx.request.body);

    // 判断是否通过验证
    if (!isValid) {
        ctx.status = 400;
        ctx.body = errors;
        return;
    }

    const findResult = await User.find({ email });
    if (findResult.length > 0) { // 查到
        ctx.status = 500;
        ctx.body = { msg: '邮箱已被占用!' };
    } else {
        // 没查到
        // 使用全球公认头像
        const avatar = gravatar.url(email, { s: '200', r: 'pg', d: 'mm' });
        const newUser = new User({
            name,
            email,
            avatar,
            password: encrypt(ctx.request.body.password)
        });

        // 存储到数据库
        await newUser
            .save()
            .then(user => {
                ctx.body = user;
            }).catch(err => {
                console.log(err);
            });

        // 返回json数据
        ctx.body = newUser;
    }

});

/**
 * @route POST api/users/login
 * @desc 登录接口地址 返回token
 * @access 接口是公开的
 */
router.post('/login', async ctx => {
    const { errors, isValid } = validateLoginInput(ctx.request.body);

    // 判断是否通过验证
    if (!isValid) {
        ctx.status = 400;
        ctx.body = errors;
        return;
    }
    // 查询
    const { email, password } = ctx.request.body;
    const findResult = await User.find({ email });
    const user = findResult[0];

    // 判断查没查到
    if (findResult.length == 0) {
        ctx.status = 404;
        ctx.body = { msg: '用户不存在!' };
        return;
    }
    // 查到后，验证密码
    const result = await decrypt(password, findResult[0].password);

    // 验证通过
    if (result) {
        // 返回 token
        const payload = { id: user.id, name: user.name, avatar: user.avatar };
        const token = jwt.sign(payload, secretOrKey, { expiresIn: 3600 });

        ctx.status = 200;
        ctx.body = { success: true, token: 'Bearer ' + token };
        return;
    }

    ctx.status = 400;
    ctx.body = { msg: '密码错误!' };


});

/**
 * @route GET api/users/current
 * @desc 登录接口地址 返回用户信息
 * @access 接口是私密的
 */
router.get('/current', passport.authenticate('jwt', { session: false }), async ctx => {
    ctx.body = ctx.state.user;
});

module.exports = router.routes();
